package com.caiheng.api.service.setmeal.impl;

import cn.hutool.core.collection.CollUtil;
import com.alipay.api.domain.Voucher;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.dao.estate.EstateMapper;
import com.caiheng.api.dao.platform.SplitAccountRecordMapper;
import com.caiheng.api.dao.setmeal.SetMealInfoGivenRecordMapper;
import com.caiheng.api.dao.setmeal.SetMealInfoMapper;
import com.caiheng.api.dao.setmeal.SetMealMapper;
import com.caiheng.api.dao.setmeal.SetMealOrderMapper;
import com.caiheng.api.entity.estate.Estate;
import com.caiheng.api.entity.platform.*;
import com.caiheng.api.entity.setmeal.*;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.exception.TransactionalException;
import com.caiheng.api.service.base.impl.BaseServiceImpl;
import com.caiheng.api.service.platfom.*;
import com.caiheng.api.service.setmeal.SetMealInfoGivenService;
import com.caiheng.api.service.setmeal.SetMealOrderService;
import com.caiheng.api.util.OrderUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 套餐活动支付订单Service业务层处理
 *
 * @author ruoyi
 * @date 2022-06-06
 */
@Service
public class SetMealOrderServiceImpl extends BaseServiceImpl<SetMealOrderMapper, SetMealOrder> implements SetMealOrderService {

    @Resource
    private SetMealOrderMapper mealOrderMapper;
    @Resource
    private SetMealMapper mealMapper;
    @Resource
    private SetMealInfoMapper mealInfoMapper;
    @Resource
    private EstateMapper estateMapper;
    @Resource
    private SetMealInfoGivenService mealInfoGivenService;
    @Resource
    private SetMealInfoGivenRecordMapper mealInfoGivenRecordMapper;
    @Resource
    private SplitAccountService splitAccountService;
    @Resource
    private SplitAccountRecordMapper accountRecordMapper;
    @Resource
    private ParameterService parameterService;
    @Resource
    private PlatformPayService platformPayService;


    @Override
    @Transactional
    public int addOrder(User user, SetMeal setMeal, SetMealInfo setMealInfo) {
        SetMealOrder mealOrder = new SetMealOrder();
        int ret = 0;
        try{
            PlatformPay platformPay = platformPayService.getDefaultAccount();
            Parameter parameter = parameterService.getParameterById(1);
            String orderNo = OrderUtil.getPayNo(platformPay.getSysCode());
            mealOrder.setCreateTime(new Date());
            mealOrder.setUserId(user.getId());
            mealOrder.setStatus(0);
            mealOrder.setMealId(setMeal.getId());
            mealOrder.setMealInfoId(setMealInfo.getId());
            mealOrder.setEstateId(user.getEstateId());
            mealOrder.setIsDel("0");
            mealOrder.setOrderNo(orderNo);
            mealOrder.setNickName(user.getNickName());
            mealOrder.setPhoneNum(user.getPhoneNum());


            mealOrder.setPayType(parameter.getSetMealPayPlatform());

            if(platformPay!=null){
                mealOrder.setPayPlatformId(platformPay.getId());
            }


            mealOrder.setFee(new BigDecimal(setMealInfo.getPayMoney().doubleValue() * 0.06 / 100));
            mealOrder.setOutTradeNo(orderNo);
            mealOrder.setPayNo(orderNo);
            mealOrder.setEstateId(user.getEstateId());
//            double totalMoney = setMealInfo.getMealMoney().doubleValue() + setMealInfo.getMealGiveMoney().doubleValue();
            mealOrder.setTotalPrice(setMealInfo.getMealMoney());
            mealOrder.setPayPrice(setMealInfo.getPayMoney());
            mealOrder.setMealMoney(setMealInfo.getMealMoney());
            mealOrder.setGivenMoney(setMealInfo.getMealGiveMoney());
            mealOrder.setIsHasReward(setMealInfo.getIsHasReward());
            mealOrder.setRewardVerify(0);//未核销状态
            mealOrder.setVerifyContent(setMealInfo.getRemark());
            mealOrder.setTotalNum(1);
            Estate estate = estateMapper.selectById(user.getEstateId());
            if(estate!=null){
                mealOrder.setPropertyId(estate.getPropertyId());
            }
            ret = mealOrderMapper.insert(mealOrder);
            if(ret <= 0){
                throw new TransactionalException("mealOrderMapper insert error");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        if(ret > 0){
            return mealOrder.getId();
        }
        return 0;
    }

    @Override
    @Transactional
    public int buyMeal(SetMealOrder mealOrder) {
        int ret = 0;
        try{
            //修改订单状态
            ret = mealOrderMapper.updateById(mealOrder);
            if(ret <= 0){
                throw new TransactionalException("mealOrderMapper updateById error");
            }


            //账户类型   0 - 平台   1 - 物业  2 -  小区  3 - 商家   4 - 个人
            SplitAccount splitAccount = splitAccountService.getAccountByUserId(mealOrder.getUserId(),4,mealOrder.getUserId());
            if(splitAccount == null){
                splitAccount = new SplitAccount();
                splitAccount.setUserId(mealOrder.getUserId());
                splitAccount.setAccountType(4);
                splitAccount.setSplitMoney(new BigDecimal(0));
                double totalMoney = mealOrder.getMealMoney().doubleValue() + mealOrder.getGivenMoney().doubleValue();
                splitAccount.setChargerMoney(new BigDecimal(totalMoney));
                splitAccount.setIsAdmin(0);
                splitAccount.setAccountId(mealOrder.getUserId());
                splitAccount.setFreezen(new BigDecimal(0));
                boolean bl = splitAccountService.save(splitAccount);
                if(!bl){
                    throw new TransactionalException("splitAccountService updateById error");
                }


                SplitAccountRecord splitAccountRecord = new SplitAccountRecord();
                splitAccountRecord.setUserId(mealOrder.getUserId());
                splitAccountRecord.setAccountId(mealOrder.getUserId());
                splitAccountRecord.setCreateTime(new Date());
                splitAccountRecord.setSplitMoney(mealOrder.getMealMoney());
                //动账类型  0 - 提现 1 - 充值 2 - 分成增加  3 - 商家的结算款  4 - 充电赠送  5 - 充电余额支付  6 - 购买充电套餐
                splitAccountRecord.setFromType(6);
                //1 - 进账  0 - 出账
                splitAccountRecord.setInOrOut(1);//进账
                splitAccountRecord.setRemark("购买充电套餐到账");//进账
                ret = accountRecordMapper.insert(splitAccountRecord);
                if(ret <= 0){
                    throw new TransactionalException("accountRecordMapper updateById error");
                }


                if( mealOrder.getGivenMoney().doubleValue() > 0){
                    SplitAccountRecord splitAccountRecord1 = new SplitAccountRecord();
                    splitAccountRecord1.setUserId(mealOrder.getUserId());
                    splitAccountRecord1.setAccountId(mealOrder.getUserId());
                    splitAccountRecord1.setCreateTime(new Date());
                    splitAccountRecord1.setSplitMoney(mealOrder.getMealMoney());
                    //动账类型  0 - 提现 1 - 充值 2 - 分成增加  3 - 商家的结算款  4 - 充电赠送  5 - 充电余额支付  6 - 购买充电套餐
                    splitAccountRecord1.setFromType(4);
                    //1 - 进账  0 - 出账
                    splitAccountRecord1.setInOrOut(1);//进账
                    splitAccountRecord1.setRemark("购买充电套餐，赠送金额到账");//进账
                    ret = accountRecordMapper.insert(splitAccountRecord1);
                    if(ret <= 0){
                        throw new TransactionalException("accountRecordMapper updateById error");
                    }
                }
            }else{
                double chargerMoney = splitAccount.getChargerMoney().doubleValue();
                chargerMoney = chargerMoney + mealOrder.getMealMoney().doubleValue() + mealOrder.getGivenMoney().doubleValue();
                splitAccount.setChargerMoney(new BigDecimal(chargerMoney));
                boolean bl = splitAccountService.updateById(splitAccount);
                if(!bl){
                    throw new TransactionalException("splitAccountService updateById error");
                }

                SplitAccountRecord splitAccountRecord = new SplitAccountRecord();
                splitAccountRecord.setUserId(mealOrder.getUserId());
                splitAccountRecord.setAccountId(mealOrder.getUserId());
                splitAccountRecord.setCreateTime(new Date());
                splitAccountRecord.setSplitMoney(mealOrder.getMealMoney());
                //动账类型  0 - 提现 1 - 充值 2 - 分成增加  3 - 商家的结算款  4 - 充电赠送  5 - 充电余额支付  6 - 购买充电套餐
                splitAccountRecord.setFromType(6);
                //1 - 进账  0 - 出账
                splitAccountRecord.setInOrOut(1);//进账
                splitAccountRecord.setRemark("购买充电套餐到账");//进账
                ret = accountRecordMapper.insert(splitAccountRecord);
                if(ret <= 0){
                    throw new TransactionalException("accountRecordMapper updateById error");
                }

                if( mealOrder.getGivenMoney().doubleValue() > 0) {
                    SplitAccountRecord splitAccountRecord1 = new SplitAccountRecord();
                    splitAccountRecord1.setUserId(mealOrder.getUserId());
                    splitAccountRecord1.setAccountId(mealOrder.getUserId());
                    splitAccountRecord1.setCreateTime(new Date());
                    splitAccountRecord1.setSplitMoney(mealOrder.getMealMoney());
                    //动账类型  0 - 提现 1 - 充值 2 - 分成增加  3 - 商家的结算款  4 - 充电赠送  5 - 充电余额支付  6 - 购买充电套餐
                    splitAccountRecord1.setFromType(4);
                    //1 - 进账  0 - 出账
                    splitAccountRecord1.setInOrOut(1);//进账
                    splitAccountRecord1.setRemark("购买充电套餐，赠送金额到账");//进账
                    ret = accountRecordMapper.insert(splitAccountRecord1);
                    if (ret <= 0) {
                        throw new TransactionalException("accountRecordMapper updateById error");
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("buyMeal insert  error");
        }
        return ret;
    }

    @Override
    public List<SetMealOrder> getMyOrderList(int user_id, int state, int pageIndex, int pageSize) {
        QueryWrapper<SetMealOrder> qw = new QueryWrapper<>();
        qw.eq("user_id",user_id);
        if(state > -1){
            if(state == 1){
                Integer[] states = { 0, 1};
                qw.in("status", Arrays.asList(states));
            }else{
                qw.eq("status",state);
            }
        }
        qw.orderByDesc("create_time");
        List<SetMealOrder> list = mealOrderMapper.getPageEntityList(qw,pageIndex,pageSize);
        if(CollUtil.isNotEmpty(list)){
            for (SetMealOrder order : list){
                Estate estate = estateMapper.selectById(order.getEstateId());
                if(estate!=null){
                    order.setEstateName(estate.getEstateName());
                }

                SetMeal setMeal = mealMapper.selectById(order.getMealId());
                if(setMeal!= null){
                    order.setMealName(setMeal.getMealName());
                }

                SetMealInfo setMealInfo = mealInfoMapper.selectById(order.getMealInfoId());
                if(setMealInfo!= null){
                    order.setMealInfoName(setMealInfo.getMealInfoName());
                }

                double totalMealMoney = order.getGivenMoney().doubleValue() + order.getMealMoney().doubleValue();
                order.setTotalMealMoney(totalMealMoney);
            }
        }
        return list;
    }
}
